package mil.af.amc.adpetracker.dao.hibernate;

import mil.af.amc.adpetracker.dao.UserDao;
import mil.af.amc.adpetracker.model.Organization;
import mil.af.amc.adpetracker.model.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;


/**
 * Created by IntelliJ IDEA.
 * User: schevus.osborne
 * Date: Feb 1, 2007
 * Time: 1:04:23 PM
 */
@Service("userDao")
public class HibernateUserDao extends HibernateGenericDao<User> implements UserDao {

    public HibernateUserDao(Class<User> type) {
        super(type);
    }

    public HibernateUserDao() {
        super(User.class);
    }

    private static Log log = LogFactory.getLog(HibernateUserDao.class);

    public Collection loadAll() {

        return getHibernateTemplate().find("from User");
    }

    public User getByUsername(final String username) {

        DetachedCriteria crit = DetachedCriteria.forClass(User.class);
        DetachedCriteria acctCrit = crit.createCriteria("account");
        acctCrit.add(Restrictions.eq("username", username.toLowerCase()));
        return (User) getHibernateTemplate().findByCriteria(crit).get(0);
    }

    @SuppressWarnings({"unchecked"})
    public List<User> getAllByOrganization(Organization o) {

        DetachedCriteria crit = DetachedCriteria.forClass(User.class);
        DetachedCriteria organizationCrit = crit.createCriteria("assignedOrganization");
        organizationCrit.add(Restrictions.ilike("name", o.getName()));

        return getHibernateTemplate().findByCriteria(crit);

    }

    @SuppressWarnings({"unchecked"})
    public List<User> getUsersWithNoAssignedEquipment(Organization o) {

        DetachedCriteria crit = DetachedCriteria.forClass(User.class);
        crit.add(Restrictions.isEmpty("assignedEquipment"));
        DetachedCriteria orgCrit = crit.createCriteria("assignedOrganization");
        orgCrit.add(Restrictions.eq("id", o.getId()));

        return (List<User>) getHibernateTemplate().findByCriteria(crit);
    }

    @SuppressWarnings({"unchecked"})
    public List<User> getUsersWithNoCpu(Organization o) {

        DetachedCriteria crit = DetachedCriteria.forClass(User.class);
        DetachedCriteria orgCrit = crit.createCriteria("assignedOrganization");
        orgCrit.add(Restrictions.eq("id", o.getId()));

        getHibernateTemplate().enableFilter("cpuOnly");

        return (List<User>) getHibernateTemplate().findByCriteria(crit);
    }

}
